<template>
  <div>
    <el-upload
      ref="upload"
      multiple
      :accept="accept"
      :limit="limit"
      :file-list="fileList"
      :show-file-list="limit !== 1"
      v-bind="uploadAttr"
    >
      <i v-if="!slingUrl || limit !== 1" class="el-icon-plus"></i>
      <img  @click="validateClear" v-else class="my-img" :src="slingUrl" alt="">
    </el-upload>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import { fetchToken } from '@/api/qnToken'
  import axios from 'axios'

  export default {
    props: {
      limit: {
        type: Number,
        default: 1
      },
      accept: {
        type: String,
        default: 'image/png, image/jpeg, image/gif'
      },
      fileList: {
        type: Array,
        default() {
          return []
        }
      },
      module: {
        type: String,
        default: 'image'
      }
    },
    data() {
      return {
        singSrc: '',
        dialogImageUrl: '',
        dialogVisible: false,
        uploadAttr: {
          action: 'https://upload.qiniu.com',
          data: {
            'x:module': this.module,
            'x:ftype': 'image',
            token: ''
          },
          'list-type': 'picture-card',
          'on-preview': this.handlePictureCardPreview,
          'on-remove': this.handleRemove,
          'on-success': this.onSuccess,
          'on-error': this.onError,
          'before-upload': this.beforeUpload,
          'http-request': this.httpRequest,
          onChange: this.onChange
        }
      }
    },
    computed: {
      slingUrl() {
        return this.singSrc || (this.fileList.length ? this.fileList[0].url : '')
      }
    },
    methods: {
      async httpRequest({ headers, filename, file, data, action, onSuccess, onError }) {
        const formData = new FormData()

        Object.entries(data).forEach(([key, value]) => {
          formData.append(key, value)
        })
        formData.append(filename, file)
        const res = await axios({
          method: 'post',
          url: action,
          data: formData,
          headers
        }).catch(onError)
        this.$emit('single-success', res.data)
        onSuccess(res.data)
      },
      async beforeUpload() {
        this.uploadAttr.data.token = await fetchToken()
      },
      validateClear() {
        if (this.limit === 1) {
          this.$refs.upload.clearFiles()
        }
      },
      onSuccess(res) {
        if (res) {
          const {base_url, path} = res
          this.singSrc = `${base_url}${path}-w750`
          this.$emit('upload-success', res)
        }
      },
      handleRemove(file, fileList) {
        this.$emit('update:fileList', fileList)
        this.$emit('on-remove', fileList, file)
      },
      onChange(file, fileList) {
        this.$emit('update:fileList', fileList)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    }
  }
</script>
<style lang="scss" scoped>
  .my-img {
    width: 146px;
    height: 146px;
  }
</style>
